import fs from 'fs'

import PROJECT from '../PROJECT'
import { ENV } from '../ENV'
import build from './build'
import buildClient from './buildClient'

const buildENV = () => (
  new Promise((ok, fail) => {
    fs.writeFile(PROJECT.BUILD.__ENV__, JSON.stringify(ENV, null, 2), err => {
      if (err) { console.log('BUILD __ENV__ FAILED: ', err); fail(err) }
      else { console.log('BUILD __ENV__ OK'); ok() }
    })
  })
  .catch(console.log)
)

const buildPROJECT = () => (
  new Promise((ok, fail) => {
    fs.writeFile(PROJECT.__PROJECT__, JSON.stringify(PROJECT, null, 2), err => {
      if (err) { console.log('BUILD __PROJECT__ FAILED: ', err); fail(err) }
      else { console.log('BUILD __PROJECT__ OK'); ok() }
    })
  })
)

export default args => (
  Promise
  .all([build(args), buildClient(args)])
  .then(() => Promise.all([buildENV(args), buildPROJECT(args)]))
)